//
//  AddDeliveryViewController.m
//  cityStar
//
//  Created by joyban on 14-12-29.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "AddDeliveryViewController.h"
#import "AddDeliveryOneCell.h"
#import "AddDeliveryTwoCell.h"

#import "UIColor+FlatUI.h"
#import "provinceViewController.h"
#import "BaseNavController.h"

//#import "CityViewController.h"
//#import "DistrictViewController.h"

#import "selectDistrict.h"
#import "selectProvince.h"
#import "selectCity.h"

NSString *const adddeliveryOneID = @"AdddeliveryOneID";
NSString *const adddeliveryTwoID = @"AdddeliveryTwoID";
NSString *const adddeliveryThreeID = @"AdddeliveryThreeID";

@interface AddDeliveryViewController ()<CSshenshiquDelegate>
{
    int i;
}
@property (weak, nonatomic) IBOutlet UITableView *addDeliveryTable;
@property (weak, nonatomic) IBOutlet UIButton *tijiaoBtn;
@property (nonatomic, strong) AddDeliveryTwoCell *deliveryTwoCell;
@property (nonatomic, strong) AddDeliveryOneCell *deliveryOneCell;
@property (nonatomic, strong) NSString *strName;
@property (nonatomic, strong) NSString *strNum;
@property (nonatomic, strong) NSString *strAddress;
@property (nonatomic, strong) ModelDelivery *DeliveryModelmessage;

@property (nonatomic, strong) NSString *strshen;
@property (nonatomic, strong) NSString *strshi;
@property (nonatomic, strong) NSString *strqu;

@property (nonatomic, strong) NSString *strshenid;
@property (nonatomic, strong) NSString *strshiid;
@property (nonatomic, strong) NSString *strquid;

@end

@implementation AddDeliveryViewController

-(id)initWithName:(ModelDelivery *)model;
{
    self = [super init];
    if (self) {
        self.DeliveryModelmessage = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.strshen = @"";
    self.strqu = @"";
    self.strshi = @"";
    self.tijiaoBtn.layer.cornerRadius = 4;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    self.navigationItem.title = @"添加收货地址";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didProvinceClick:) name:@"BackProvinvr" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didCityClick:) name:@"BackCity" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDistrictClick:) name:@"BackDistrict" object:nil];
    
    [self addBackButton];
    [self setUpTableViews];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.deliveryOneCell.shenTextFiled.text = [[self.strshen stringByAppendingString:self.strshi]stringByAppendingString:self.strqu];
}

-(void)didDistrictClick:(NSNotification *)notification
{
    int num = [(NSString *)notification.object intValue];
    self.strqu = [selectDistrict shardDistrictInfo].DistrictNameArray[num];
    self.strquid = [selectDistrict shardDistrictInfo].DistrictIdArray[num];
}

-(void)didProvinceClick:(NSNotification *)notification
{
    int num = [(NSString *)notification.object intValue];
    self.strshen = [selectProvince shardProvinceInfo].ProvinceNameArray[num];
    self.strshenid = [selectProvince shardProvinceInfo].ProvinceIdArray[num];
}

-(void)didCityClick:(NSNotification *)notification
{
    int num = [(NSString *)notification.object intValue];
    self.strshi = [selectCity shardUserInfo].cityNameArray[num];
    self.strshiid = [selectCity shardUserInfo].cityIdArray[num];
}

-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)senderdidshen:(UIButton *)btn
{
    provinceViewController *ProvinceVC = [[provinceViewController alloc]init];
    BaseNavController *baseloginNav = [[BaseNavController alloc] initWithRootViewController:ProvinceVC];
    [self presentViewController:baseloginNav animated:YES completion:^{
    }];
}

-(void)setUpTableViews
{
    [self.addDeliveryTable registerNib:[AddDeliveryOneCell nib] forCellReuseIdentifier:adddeliveryOneID];
    [self.addDeliveryTable registerNib:[AddDeliveryTwoCell nib] forCellReuseIdentifier:adddeliveryTwoID];
}

-(IBAction)return_Action:(UIButton *)sender
{

    NSString *userName = self.deliveryOneCell.NameTextFiled.text;
    NSString *phone = self.deliveryOneCell.PhoneTextFiled.text;
    NSString *mobile = self.deliveryOneCell.telPhoneTextFiled.text;
    NSString *zipcode = self.deliveryOneCell.OfficeTextField.text;
    NSString *address = self.deliveryOneCell.ardessTextField.text;
    NSString *status = @"";
    
    if(self.DeliveryModelmessage.uuid != nil)
    {
        NSString * uuid = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.uuid];
        NSString * city = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.city];
        NSString * province = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.province];
        NSString * district = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.district];
       
        if(self.strshenid != nil && ![self.strshenid isEqualToString:@""])
        {
            province = self.strshenid;
        }
        if(self.strshiid != nil && ![self.strshiid isEqualToString:@""])
        {
            city = self.strshiid;
        }
        if(self.strquid != nil && ![self.strquid isEqualToString:@""])
        {
            district = self.strquid;
        }
        
        NSDictionary *parameters = @{@"uuid":uuid,@"city":city,@"name":userName,@"address":address,@"province":province,@"district":district,@"phone":phone,@"mobile":mobile,@"zipcode":zipcode};
        [HttpRequestManager putMethod:kInterface_update parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"修改地址成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:errMsg];
            }
        }];
    }else{
       NSString * uuid = [[NSUUID UUID]UUIDString];
       NSString * city = self.strshiid;
       NSString * province = self.strshenid;
       NSString * district = self.strquid;
        if(self.deliveryTwoCell.add_select.selected == YES)
        {
            status = @"2";
        }else{
            status = @"1";
        }
        NSDictionary *parameters = @{@"uuid":uuid,@"city":city,@"name":userName,@"address":address,@"province":province,@"district":district,@"phone":phone,@"mobile":mobile,@"zipcode":zipcode,@"status":status};
        [HttpRequestManager postMethod:KInterface_AddUserAddress parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"添加地址成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                NSLog(@"%@",errMsg);
                [SVProgressHUD showErrorWithStatus:errMsg];
            }
        }];
    }
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return [AddDeliveryOneCell heightOfTableCell];
    }else{
        return [AddDeliveryTwoCell heightOfTableCell];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 220)];
    [sectionView setBackgroundColor:[UIColor colorFromHexCode:@"F5F4F1"]];
    if(section == 0)
    {
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20, tableView.bounds.size.width, 1)];
        [image setBackgroundColor:[UIColor colorFromHexCode:@"ECECEC"]];
        [sectionView addSubview:image];
    }
    return sectionView;
}


#pragma mark - UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        self.deliveryOneCell = [tableView dequeueReusableCellWithIdentifier:adddeliveryOneID];
        self.deliveryOneCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(self.DeliveryModelmessage.uuid != nil)
        {
            self.deliveryOneCell.NameTextFiled.text = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.name];
            self.deliveryOneCell.PhoneTextFiled.text = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.phone];
            self.deliveryOneCell.ardessTextField.text = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.address];
            self.deliveryOneCell.telPhoneTextFiled.text = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.mobile];
            self.deliveryOneCell.OfficeTextField.text = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.zipcode];
            NSString *string = [[self.DeliveryModelmessage.province_name stringByAppendingString:self.DeliveryModelmessage.city_name]stringByAppendingString:self.DeliveryModelmessage.district_name];
            self.deliveryOneCell.shenTextFiled.text = string;
        }
        self.deliveryOneCell.delegate = self;
        return self.deliveryOneCell;
    }else{
        self.deliveryTwoCell = [tableView dequeueReusableCellWithIdentifier:adddeliveryTwoID];
        self.deliveryTwoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(self.DeliveryModelmessage.uuid != nil)
        {
            NSString *defaul = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.is_default];
            if([defaul isEqualToString:@"1"])
            {
                self.deliveryTwoCell.add_select.selected = YES;
            }else{
                self.deliveryTwoCell.add_select.selected = NO;
            }
        }
        return self.deliveryTwoCell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        if(self.DeliveryModelmessage.uuid != nil)
        {
                NSString * uuid = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.uuid];
                NSDictionary *parameters = @{@"uuid":uuid};
                NSString *defaul = [NSString stringWithFormat:@"%@",self.DeliveryModelmessage.is_default];
                if([defaul isEqualToString:@"0"])
                {
                    [HttpRequestManager putMethod:kInterface_defaul parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                        if (success) {
                            self.deliveryTwoCell.add_select.selected = YES;
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"senderdid" object:self.deliveryOneCell.ardessTextField.text];
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"senderUUID" object:[NSString stringWithFormat:@"%@",self.DeliveryModelmessage.uuid]];
                            [SVProgressHUD showSuccessWithStatus:@"修改默认地址成功"];
                        }else{
                            [SVProgressHUD showErrorWithStatus:errMsg];
                            NSLog(@"%@",errMsg);
                        }
                    }];
                }
        }else{
            if(self.deliveryTwoCell.add_select.selected == YES)
            {
                self.deliveryTwoCell.add_select.selected = NO;
            }else{
                self.deliveryTwoCell.add_select.selected = YES;
            }
        }
    }
}

#pragma mark - UIKeyBoard Notification Methods

#pragma mark - UIKeyBoard Change Frame Notificatin Method
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.addDeliveryTable.height = CGRectGetHeight(AppBounds)-64-CGRectGetHeight(keyboardFrame);
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    self.addDeliveryTable.height = CGRectGetHeight(AppBounds) - 44 - 64 -20;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
